package com.dcm.common.advice;


import com.dcm.common.annotation.EnableResponseBodyAdvice;
import com.dcm.common.constant.Constants;
import com.dcm.common.exception.MyException;
import com.dcm.common.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author pengrongsheng
 * @date 2021/3/23
 **/
@RestControllerAdvice(annotations = EnableResponseBodyAdvice.class)
@ResponseBody
@Slf4j
public class ExceptionAdvice {

    /**
     * 处理业务异常 MyException
     *
     * @param e 业务异常
     * @return 统一响应体
     * data:null
     */
    @ExceptionHandler(MyException.class)
    public CommonResponse handleMyException(MyException e) {
        log.error(e.getMessage(), e);
        return new CommonResponse(e.getCode(), e.getMessage(), null);
    }

    /**
     * 处理未捕获的 Exception
     *
     * @param e 异常
     * @return 统一响应体
     * data:null
     */
    @ExceptionHandler(Exception.class)
    public CommonResponse handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new CommonResponse(-1, Constants.ResponseMsg.SERVICE_ERROR, null);
    }

    /**
     * 处理未捕获的 RuntimeException
     *
     * @param e 运行异常
     * @return 统一响应体
     * data:null
     */
    @ExceptionHandler(RuntimeException.class)
    public CommonResponse handleRuntimeException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return new CommonResponse(-1, Constants.ResponseMsg.SERVICE_ERROR, null);
    }

}
